package com.quartz.task;

import org.quartz.CronScheduleBuilder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;

/**
 * @描述: 基础的task
 * @类名:
 * @作者: yangshuang
 * @创建时间: 2017/8/17 19:35
 * @版本: v1.0
 */
public class BaseTask implements Job {
    @Autowired
    private Scheduler scheduler;

    @PostConstruct//等同于init-method
    public void init() {
           //需要定义jobDetail

               //需要定义jobDetail
        String jobKeyName = this.getClass().getSimpleName() + "_job";
        String group = this.getClass().getSimpleName() + " _group";
        String triggerName = this.getClass().getSimpleName() + "_trigger";

        String cronExpression = getCronExpression();
        try {

            JobKey jobKey = new JobKey(jobKeyName, group);
            TriggerKey triggerKey = new TriggerKey(triggerName, group);
            if (scheduler.checkExists(jobKey)) {//查看job是否存在
                if (!scheduler.checkExists(triggerKey)) {//检查是否有job对应的trigger存在
                    Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).build();
                    scheduler.rescheduleJob(triggerKey, trigger);
                } else {
                    Trigger.TriggerState triggerState = scheduler.getTriggerState(triggerKey);
                    if (!triggerState.equals(Trigger.TriggerState.NORMAL)) {
                        log.info("quartz恢复任务");
                        scheduler.resumeJob(jobKey);
                    }
                }
            } else {
                //新建
                Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).build();
                JobDetail newJobDetail = JobBuilder.newJob(this.getClass()).withIdentity(jobKey).build();
                scheduler.scheduleJob(newJobDetail, trigger);
            }


        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    public String getCronExpression() {
        return null;
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //并没有真正意义上的实现
    }
}
